package com.kstudio.videocapture.listfile;

import java.util.ArrayList;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import com.kstudio.videocapture.R;
import com.kstudio.videocapture.listfile.KFileListAdapterWrapper.KFileListCheckClickListener;
import com.kstudio.videocapture.util.KLog;
import com.kstudio.videocapture.util.KUtil;
import com.kstudio.videocapture.util.bitmapload.BitmapCache;
import com.kstudio.videocapture.util.bitmapload.BitmapCacheParam;

public class KFileListAdapter extends ArrayAdapter<KFileListItem> {
    private final KLog log = new KLog("KFileList");

    public static final int MODE_LIST   = 0x0001;
    public static final int MODE_CHECK  = 0x0002;

    private static final int MSG_UI_UPDATE = 0x0001;

    private static final int ICON_FOLDER        = R.drawable.klist_folder;
    private static final int ICON_FILE          = R.drawable.klist_file;
    private static final int ICON_EXTRA_VIDEO   = R.drawable.klist_video_icon;
    private static final int ICON_EXTRA_PICTURE = R.drawable.klist_picture_icon;

    private final LayoutInflater         mInflater;
    private final MediaMetadataRetriever mRetriever;
    private BitmapCache mBitmapCache;

    private int mMode;

    private int mMainIconWidth;
    private int mMainIconHeight;
    private KFileListCheckClickListener mListener;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UI_UPDATE:
                    BitmapCacheParam<?> param = (BitmapCacheParam<?>) msg.obj;

                    KFileListAdapterWrapper viewWrapper = (KFileListAdapterWrapper)param.getParam();
                    if(viewWrapper.getPath().equals(param.getPath())) {

                        if(param.getBitmap() == null) {
                            KFileListItem item = getItem(viewWrapper.getPosition());

                            item.setFileType(KFileListItem.FILE);
                            viewWrapper.getIcon().setMainIconId(ICON_FILE);
                            viewWrapper.getIcon().setSubIconId(KFileListViewSubIcon.SubIconNone);
                            viewWrapper.getDuration().setVisibility(View.GONE);
                        } else {
                            viewWrapper.getIcon().setMainIconBMP(param.getBitmap());
                        }
                    }
                break;
            }
        }
    };

    public KFileListAdapter(Context context, ArrayList<KFileListItem> objects, int mainIconWidth, int mainIconHeight, KFileListCheckClickListener l) {
        super(context, 0, objects);

        mMainIconWidth = mainIconWidth;
        mMainIconHeight = mainIconHeight;

        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mRetriever = new MediaMetadataRetriever();

        mMode = MODE_LIST;
        mListener = l;

        final int largeMemClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getLargeMemoryClass();
        final int largeDiskSize = 1024 * 1024 * largeMemClass / 2;
        final int largeCacheSize = 1024 * 1024 * largeMemClass / 32;

        mBitmapCache = new BitmapCache(context, "KFileList", largeCacheSize, largeDiskSize) {
            @Override
            public Bitmap onLoadBitmap(String filename) {
                int fileType = KFileListItem.getFileType(filename);
                Bitmap bm = null;

                if(fileType == KFileListItem.VIDEO) {
                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    Bitmap frame = null;
                    try {
                        retriever.setDataSource(filename);
                        frame = retriever.getFrameAtTime();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if(frame != null) {
                        bm = KUtil.resizedBitmapOnRatio(frame, mMainIconWidth, mMainIconHeight);
                        frame.recycle();
                    } else {
                        Log.i("KKH","onLoadBitmap null path = "+filename);
                    }
                } else if(fileType == KFileListItem.PICTURE) {
                    bm = KUtil.fastLoadBitmapResizedOnRatio(filename, mMainIconWidth, mMainIconHeight);
                }
                return bm;
            }

            @Override
            public void onLoadDone(BitmapCacheParam<?> param) {
                Message msg = mHandler.obtainMessage();
                msg.what = MSG_UI_UPDATE;
                msg.obj = param;
                mHandler.sendMessage(msg);
            }
        };
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        KFileListAdapterWrapper viewWrapper;

        if(view == null) {
            view = mInflater.inflate(R.layout.file_list_row, null);
            viewWrapper = new KFileListAdapterWrapper(view, mListener);
            view.setTag(viewWrapper);
        } else {
            viewWrapper = (KFileListAdapterWrapper)view.getTag();
        }

        final KFileListItem data = this.getItem(position);

        if(data != null) {
            Bitmap bm = null;
            viewWrapper.setPosition(position);
            viewWrapper.setItem(data);

            if(data.getFileType() == KFileListItem.FOLDERUP) {
                viewWrapper.getIcon().setMainIconId(ICON_FOLDER);
                viewWrapper.getIcon().setSubIconId(KFileListViewSubIcon.SubIconNone);
                viewWrapper.getName().setText(data.getName());
                viewWrapper.getDuration().setVisibility(View.GONE);
                viewWrapper.getCheckNo().setVisibility(View.GONE);
                viewWrapper.getCheckYes().setVisibility(View.GONE);
            } else if(data.getFileType() == KFileListItem.FOLDER) {
                viewWrapper.getIcon().setMainIconId(ICON_FOLDER);
                viewWrapper.getIcon().setSubIconId(KFileListViewSubIcon.SubIconNone);
                viewWrapper.getName().setText(data.getName());
                viewWrapper.getDuration().setVisibility(View.GONE);
                viewWrapper.getCheckNo().setVisibility(View.GONE);
                viewWrapper.getCheckYes().setVisibility(View.GONE);
            } else if(data.getFileType() == KFileListItem.VIDEO) {
                bm = mBitmapCache.load(new BitmapCacheParam<KFileListAdapterWrapper>(data.getPath(), viewWrapper));
                if(bm == null) {
                    viewWrapper.getIcon().setMainIconId(ICON_FILE);
                } else {
                    viewWrapper.getIcon().setMainIconBMP(bm);
                }
                viewWrapper.getIcon().setSubIconId(ICON_EXTRA_VIDEO);
                viewWrapper.getName().setText(data.getName());
                if(mMode == MODE_CHECK && viewWrapper.getChecked()) {
                	viewWrapper.getCheckNo().setVisibility(View.GONE);
                	viewWrapper.getCheckYes().setVisibility(View.VISIBLE);
                	viewWrapper.getDuration().setVisibility(View.GONE);
                } else if(mMode == MODE_CHECK && !viewWrapper.getChecked()) {
                    viewWrapper.getCheckNo().setVisibility(View.VISIBLE);
                    viewWrapper.getCheckYes().setVisibility(View.GONE);
                    viewWrapper.getDuration().setVisibility(View.GONE);
                } else {
	                viewWrapper.getDuration().setVisibility(View.VISIBLE);
	                if(data.getDuration() == 0) {
	                    try {
	                        mRetriever.setDataSource(data.getPath());
	                        data.setDuration(Integer.parseInt(mRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)));
	                    } catch(Exception e) {
	                        e.printStackTrace();
	                    }
	                }
	                viewWrapper.getDuration().setText(formatTime(data.getDuration()));
	                viewWrapper.getCheckNo().setVisibility(View.GONE);
	                viewWrapper.getCheckYes().setVisibility(View.GONE);
                }
            } else if(data.getFileType() == KFileListItem.PICTURE) {
                bm = mBitmapCache.load(new BitmapCacheParam<KFileListAdapterWrapper>(data.getPath(), viewWrapper));
                if(bm == null) {
                    viewWrapper.getIcon().setMainIconId(ICON_FILE);
                } else {
                    viewWrapper.getIcon().setMainIconBMP(bm);
                }
                viewWrapper.getIcon().setSubIconId(ICON_EXTRA_PICTURE);
                viewWrapper.getName().setText(data.getName());
                viewWrapper.getDuration().setVisibility(View.GONE);
            } else {
                viewWrapper.getIcon().setMainIconId(ICON_FILE);
                viewWrapper.getIcon().setSubIconId(KFileListViewSubIcon.SubIconNone);
                viewWrapper.getName().setText(data.getName());
                viewWrapper.getDuration().setVisibility(View.GONE);
            }
        }
        return view;
    }

    public void stop() {
        mBitmapCache.stop();
    }

    public void fileCheckEnable(int mode) {
        mMode = mode;
    }

    private String formatTime(int duration) {
        int hour = (duration/1000) / 3600;
        int min = ((duration/1000) % 3600) / 60;
        int sec = (duration/1000) % 60;

        if(hour == 0) {
            return String.format("%02d:%02d", min, sec);
        } else {
            return String.format("%02d:%02d:%02d", hour, min, sec);
        }
    }
}
